﻿
using UnityModule;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEditor;
using LitJson;
using UnityEngine;
public class UpSpine
{
    static string[] dir_paths = new string[] {
        Application.dataPath
    };

    static string[] special_paths = new string[] {
        "tiandiwuji_Material",
        "jueshiwushuang_Material",
        "jiuxiaoqijian_Material",
        "bfkx_Material",
        "mmrh_Material",
        "dishikun_Material",
        "shanqiwuzong3_Material",
        "kanyidao_Material",
        "jhyrs_Material",
        "luohualiushui_Material",
        "luojianyouhen_Material",
        "ncjsd_Material",

        "xiaoqing_Material",
        "tutu_Material",      
        "zhengjiahouzi_Material",
        "huayan_Material",
        "huhu_Material",
    };

    static Dictionary<string, string> matDic = new Dictionary<string, string>{
        {"Universal Render Pipeline/Lit","Mobile/Diffuse"},
        {"Universal Render Pipeline/Simple Lit","Mobile/Diffuse"},
        {"Universal Render Pipeline/Unlit","Mobile/Unlit (Supports Lightmap)"},
    };

    public static void PrintShader()
    {
        if (Selection.activeObject is Material)
        {
            var tmpmat = Selection.activeObject as Material;
            Debug.LogError(tmpmat.shader);
        }
    }
    public static void CheckMat()
    {
        var dir = new DirectoryInfo(Application.dataPath);
        var mat_files = dir.GetFiles("*.mat", SearchOption.AllDirectories);

        foreach (var item in mat_files)
        {
            string assetPath = item.FullName.Substring(item.FullName.IndexOf("Assets"));
            Material mat = AssetDatabase.LoadAssetAtPath<Material>(assetPath);

            //"Hidden/InternalErrorShader"
            //Contains("Universal")
            if (mat.shader.name.Equals("TTShader/add"))
            {
                Debug.LogError(mat.name + " " + mat.shader.name);
            }
        }
        AssetDatabase.Refresh();
    }

    public static void UpgradeMat()
    {
        var dir = new DirectoryInfo(Application.dataPath);
        var mat_files = dir.GetFiles("*.mat", SearchOption.AllDirectories);

        foreach (var item in mat_files)
        {
            string assetPath = item.FullName.Substring(item.FullName.IndexOf("Assets"));
            Material mat = AssetDatabase.LoadAssetAtPath<Material>(assetPath);
            if (matDic.ContainsKey(mat.shader.name))
            {
                mat.shader = Shader.Find(matDic[mat.shader.name]);
                // Debug.LogError(mat.name + " " + mat.shader.name);
            }
            // if (mat.shader.name.Contains("Universal"))
            // {
            //     Debug.LogError(mat.name);
            //     Debug.LogError(mat.shader.name);
            // }
        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
    public static void Upgrade()
    {
        foreach (var path in dir_paths)
        {
            var dir = new DirectoryInfo(path);
            var files = dir.GetFiles("*.json", SearchOption.AllDirectories);

            foreach (var item in files)
            {
                UpgradeSpine(item.FullName);
            }

            var mat_files = dir.GetFiles("*.mat", SearchOption.AllDirectories);

            foreach (var item in mat_files)
            {
                string assetPath = item.FullName.Substring(item.FullName.IndexOf("Assets"));
                if (assetPath.Contains("_Material"))
                {
                    bool find = false;
                    foreach (var subItem in special_paths)
                    {
                        if (assetPath.Contains(subItem))
                        {
                            find = true;
                            break;
                        }
                    }
                    Material mat = AssetDatabase.LoadAssetAtPath<Material>(assetPath);
                    if (find)
                    {
                        mat.shader = Shader.Find("Spine/Skeleton Tint");
                    }
                    else
                    {
                        mat.shader = Shader.Find("Spine/SkeletonGraphic");
                    }

                    // 
                    // Debug.LogError(assetPath + " " + mat.shader.name);
                }
            }
        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }

    private static void UpgradeSpine(string path)
    {
        // Debug.LogError("Handle "+path);
        JsonData data = JsonMapper.ToObject(File.ReadAllText(path));

        if (!data.ContainsKey("skins"))
        {
            Debug.Log("Not Handle " + path);
            return;
        }
        if (!data["skins"].IsArray)
        {
            JsonData skins = new JsonData();
            JsonData tmp_data = new JsonData();
            tmp_data["name"] = "default";
            tmp_data["attachments"] = data["skins"]["default"];
            skins.Add(tmp_data);

            data["skins"] = skins;
        }

        data["skeleton"]["spine"] = "3.8.99";

        JsonData tmp;

        foreach (KeyValuePair<string, JsonData> item in data["animations"])
        {
            foreach (KeyValuePair<string, JsonData> subitem in item.Value)
            {
                tmp = subitem.Value;

                if (subitem.Key == "deform")
                {
                    tmp = tmp["default"];
                }
                if (!tmp.IsArray)
                {
                    TransformNode(tmp);
                }
            }
        }
        File.WriteAllText(path, JsonMapper.ToJson(data));
    }

    private static void TransformNode(JsonData data)
    {
        foreach (KeyValuePair<string, JsonData> item in data)
        {
            foreach (KeyValuePair<string, JsonData> subitem in item.Value)
            {
                TransformCurve(item.Value, subitem.Key);
            }
        }
    }

    private static void TransformCurve(JsonData data, string key)
    {
        if (data.ContainsKey(key))
        {
            foreach (JsonData subitem in data[key])
            {
                if (subitem.ContainsKey("curve"))
                {
                    JsonData curve = subitem["curve"];
                    if (curve.IsArray)
                    {

                        double c1 = double.Parse(curve[0].ToString());
                        double c2 = double.Parse(curve[1].ToString());
                        double c3 = double.Parse(curve[2].ToString());
                        double c4 = double.Parse(curve[3].ToString());

                        subitem["curve"] = c1;
                        if (c2 != 0)
                        {
                            subitem["c2"] = c2;
                        }
                        subitem["c3"] = c3;
                        if (c4 != 1)
                        {
                            subitem["c4"] = c4;
                        }
                    }
                }
            }
        }
    }
}

